import {useNavigate,useLocation} from "react-router-dom";
import { Outlet } from 'react-router-dom'
import {checkRouterAuth} from './index'
import {AuthLogin} from '../common/Auth.js'
import {useEffect,useState} from 'react'
import {getLoginUserAllPer} from '../common/Auth.js'
const RouterBeforeEach = ()=>{
  const navigate = useNavigate()
  const location = useLocation()
  const [auth,setAuth] = useState(false)
  useEffect(()=>{
    let obj = checkRouterAuth(location.pathname)
    let flag=false
    getLoginUserAllPer().then((data)=>{
      data.map((item)=>{
        if(obj.path===item.url||obj.code==='all'){
          if(obj.code===item.code||obj.code==='all'){
            flag=true
          }
        }
      })
      let blLogin =AuthLogin()
      if(blLogin===false){
        if(obj&&obj.auth===false)
        {
          setAuth(false)
          navigate('/', {replace: true})
        }
      }
      else if(flag===false){
          setAuth(false)
          navigate('/', {replace: true})
      }
      else{
        setAuth(true)
      }
    })
  },[])
  return auth?<Outlet/>:null
} 
export default RouterBeforeEach